package com.zide.common.utils;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import org.apache.commons.lang3.time.DateFormatUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAdjusters;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 时间工具类
 *
 * @author zide
 */
public class DateUtils extends org.apache.commons.lang3.time.DateUtils {

    public static String YYYY_MM_DD = "yyyy-MM-dd";

    public static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";

    public static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";

    private static String[] parsePatterns = {
            "yyyy-MM-dd" , "yyyy-MM-dd HH:mm:ss" , "yyyy-MM-dd HH:mm" , "yyyy-MM" ,
            "yyyy/MM/dd" , "yyyy/MM/dd HH:mm:ss" , "yyyy/MM/dd HH:mm" , "yyyy/MM" ,
            "yyyy.MM.dd" , "yyyy.MM.dd HH:mm:ss" , "yyyy.MM.dd HH:mm" , "yyyy.MM"};
    private static final Map<Integer,String> dayWeekMap = new HashMap<>();
    // 定义公用时间格式
    private static final String LOCAL_DATE = "yyyy-MM-dd";
    private static final String LOCAL_DATE_NIAN_YUE = "yyyy年MM月";
    private static final String LOCAL_DATE_TIME = "yyyy-MM-dd HH:mm:ss";
    static {
        dayWeekMap.put(1,"周一");
        dayWeekMap.put(2,"周二");
        dayWeekMap.put(3,"周三");
        dayWeekMap.put(4,"周四");
        dayWeekMap.put(5,"周五");
        dayWeekMap.put(6,"周六");
        dayWeekMap.put(7,"周日");
    }

    /**
     * 获取当前日期, 默认格式为yyyy-MM-dd
     *
     * @return String
     */
    public static String getDate() {
        return dateTimeNow(YYYY_MM_DD);
    }

    public static final String getTime() {
        return dateTimeNow(YYYY_MM_DD_HH_MM_SS);
    }

    public static final String dateTimeNow() {
        return dateTimeNow(YYYYMMDDHHMMSS);
    }

    public static final String dateTimeNow(final String format) {
        return parseDateToStr(format, new Date());
    }

    public static final String dateTime(final Date date) {
        return parseDateToStr(YYYY_MM_DD, date);
    }

    public static final String parseDateToStr(final String format, final Date date) {
        return new SimpleDateFormat(format).format(date);
    }

    /**
     * 日期路径 即年/月/日 如2018/08/08
     */
    public static final String datePath() {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyy/MM/dd");
    }


    /**
     * 日期型字符串转化为日期 格式
     */
    public static Date parseDate(Object str) {
        if (str == null) {
            return null;
        }
        try {
            return parseDate(str.toString(), parsePatterns);
        } catch (ParseException e) {
            return null;
        }
    }

    /**
     * 根据出生年月日计算年龄
     * @param birth
     * @return
     */
    public static int getAgeForBirth(String birth) {
        try {
            int age = 0;
            if (StrUtil.isEmpty(birth)) {
                return age;
            }
            // 2023-04-24
            int year = Integer.valueOf(birth.substring(0, 4));
            int month = Integer.valueOf(birth.substring(5, 7));
            int day = Integer.valueOf(birth.substring(8));
            Calendar cal = Calendar.getInstance();
            age = cal.get(Calendar.YEAR) - year;
            // 周岁计算
            if (cal.get(Calendar.MONTH) < (month - 1) || (cal.get(Calendar.MONTH) == (month - 1) && cal.get(Calendar.DATE) < day)) {
                age--;
            }
            return age;
        } catch (Exception e) {
            e.getMessage();
        }
        return -1;
    }
    public static String getTimeDiff(LocalDateTime date) {
        if (ObjectUtil.isNull(date)) {
            return null;
        }
        String term = "";
        try {
            LocalDateTime now = LocalDateTime.now();
            int start_year = date.getYear();
            int start_month = date.getMonthValue();
            int start_day = date.getDayOfMonth();
            int end_year = now.getYear();
            int end_month = now.getMonthValue();
            int end_day = now.getDayOfMonth();
            long y = ChronoUnit.YEARS.between(date, now);                    //获取两个日期间隔年
            long m = ChronoUnit.MONTHS.between(date, now);                   //获取两个日期间隔月
            long d = ChronoUnit.DAYS.between(date, now);                     //获取两个日期间隔天

            int lastDayOfEndDate = now.with(TemporalAdjusters.lastDayOfMonth()).getDayOfMonth();     //获取某个月的最后一天
            if (start_year == end_year) {
                if (start_day == end_day || lastDayOfEndDate == end_day) {
                    m = end_month - start_month;
                } else {
                    d = now.getDayOfMonth();        //获取传入时间对象的Day值
                }
            } else {
                if (m >= 12) {
                    m = m - y * 12;
                }
                if (start_day == end_day || lastDayOfEndDate == end_day) {
                    d = 0;
                } else {
                    d = now.getDayOfMonth();
                }
            }

            if(y != 0) {
                term = y + "年";
            } else if (m != 0) {
                term = m + "月";
            }else {
                term = d + "天";
            }
            // term = (y == 0 ? "" : y + "年") + (m == 0 ? "" : +m + "月") + (d == 0 ? "" : d + "天");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return term;
    }

    public static String getTimeDiffToMil(LocalDateTime createTime) {
        if (ObjectUtil.isNull(createTime)) {
            return null;
        }
        String term = "";
        try {
            LocalDateTime now = LocalDateTime.now();

            long y = ChronoUnit.YEARS.between(createTime, now);                    //获取两个日期间隔年
            long m = ChronoUnit.MONTHS.between(createTime, now);                   //获取两个日期间隔月
            long d = ChronoUnit.DAYS.between(createTime, now);                     //获取两个日期间隔天
            long h = ChronoUnit.HOURS.between(createTime, now);                     //获取两个日期间隔小时
            long f = ChronoUnit.MINUTES.between(createTime, now);                     //获取两个日期间隔分
            long s = ChronoUnit.SECONDS.between(createTime, now);                     //获取两个日期间隔秒

            int lastDayOfEndDate = now.with(TemporalAdjusters.lastDayOfMonth()).getDayOfMonth();     //获取某个月的最后一天
            // 同一年
            if(y == 0) {
                // 判断月份
                if(m == 0) {
                    // 判断天
                    if(d == 0) {
                        // 判断小时
                        if(h == 0) {
                            // 判断分钟
                            if(f == 0) {
                                // 判断秒
                                if(s == 0) {
                                    term = "刚刚";
                                }else term = s + "秒前";
                            }else {
                                term = f + "分前";
                            }
                        }else {
                            term = h +"小时前";
                        }
                    }else {
                        term = d + "天前";
                    }
                }else {
                    term = m + "月前";
                }
            }else {
                term = y + "年前";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return term;

    }

    public static String parseWeek(LocalDate date) {
        DayOfWeek dayOfWeek = date.getDayOfWeek();
        int value = dayOfWeek.getValue();
        String week = dayWeekMap.get(value);
        return week;
    }



    public static String getCurrentInterval2(LocalDateTime dateTime) {
        // 如果是当天
        LocalDate currentDate = LocalDateTime.now().toLocalDate();
        LocalDate date = dateTime.toLocalDate();
        if (currentDate.equals(date)) {
            int hour = dateTime.getHour();
            int minute = dateTime.getMinute();
            String strHour = hour + "";
            String strMinute = minute + "";
            if (hour < 10) {
                strHour = "0" + hour;
            }
            if (minute < 10) {
                strMinute = "0" + minute;
            }
            return strHour + ":" + strMinute;
        }
        // 判断是否为昨天
        if (currentDate.minusDays(1).equals(date)) {
            return "昨天";
        }
        int dayOfMonth = dateTime.getDayOfMonth();
        int monthValue = dateTime.getMonthValue();
        String strdayOfMonth = dayOfMonth + "";
        String strmonthValue = monthValue + "";
        if (dayOfMonth < 10) {
            strdayOfMonth = "0" + dayOfMonth;
        }
        if (monthValue < 10) {
            strmonthValue = "0" + monthValue;
        }
        return strdayOfMonth + "-" + strmonthValue;
    }

    /**
     * 计算时间差
     *
     * @param endDate   最后时间
     * @param startTime 开始时间
     * @return 时间差（天/小时/分钟）
     */
    public static String timeDistance(Date endDate, Date startTime) {
        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        // long ns = 1000;
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - startTime.getTime();
        // 计算差多少天
        long day = diff / nd;
        // 计算差多少小时
        long hour = diff % nd / nh;
        // 计算差多少分钟
        long min = diff % nd % nh / nm;
        // 计算差多少秒//输出结果
        // long sec = diff % nd % nh % nm / ns;
        return day + "天" + hour + "小时" + min + "分钟";
    }

    /**
     * 增加 LocalDateTime ==> Date
     */
    public static Date toDate(LocalDateTime temporalAccessor) {
        ZonedDateTime zdt = temporalAccessor.atZone(ZoneId.systemDefault());
        return Date.from(zdt.toInstant());
    }

    /**
     * 增加 LocalDate ==> Date
     */
    public static Date toDate(LocalDate temporalAccessor) {
        LocalDateTime localDateTime = LocalDateTime.of(temporalAccessor, LocalTime.of(0, 0, 0));
        ZonedDateTime zdt = localDateTime.atZone(ZoneId.systemDefault());
        return Date.from(zdt.toInstant());
    }
}
